/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年9月16日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.scattered2.myrpc.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import test.scattered2.myrpc.server.RPCRequest;

/**
 * @Type RPCNetTransport
 * @Desc
 * @author 52489
 * @date 2019年9月16日
 * @Version V1.0
 */
public class RPCNetTransport {
    String host;
    Integer port;

    /**
     * @param host
     * @param port
     */
    public RPCNetTransport(String host, Integer port) {
        super();
        this.host = host;
        this.port = port;
    }

    private Socket newSocket() {
        System.out.println("创建一个新的socket连接");
        Socket socket;
        try {
            socket = new Socket(host, port);
        } catch (Exception e) {
            throw new RuntimeException("连接失败");
        }
        return socket;
    }

    public Object sendRequest(RPCRequest request) {
        Socket socket;
        socket = newSocket();
        try {
            System.out.println("客户端调用");
            OutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ((ObjectOutputStream) outputStream).writeObject(request);
            outputStream.flush();
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            Object result = objectInputStream.readObject();
            objectInputStream.close();
            outputStream.close();
            return result;
        } catch (Exception e) {
            throw new RuntimeException("发送数据异常：" + e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
